package com.zzl.test.oss.demo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.http.HttpMethod;

import com.zzl.mine.util.Base64;

/**
 * @description 阿里云HMACSHA1签名
 * @author houjie
 * @date 2018年12月5日 下午3:21:34
 */
public class HMACSHA1Sign {
	
	private static final String MAC_NAME ="HmacSHA1";
	private static final String ENCODING ="UTF-8";
	/**
	 * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
	 *
	 *@param encryptText 被签名的字符串
	 *@param encryptKey  密钥
	 *@return
	 *@throws Exception
	 */
	public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
		byte[] data = encryptKey.getBytes(ENCODING);
		//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
		SecretKey secretKey = new SecretKeySpec(data,MAC_NAME);
		//生成一个指定 Mac 算法的 Mac 对象
		Mac mac = Mac.getInstance(MAC_NAME);
		//用给定密钥初始化 Mac 对象
		mac.init(secretKey);
		byte[] text = encryptText.getBytes(ENCODING);
		//完成 Mac 操作
		return mac.doFinal(text);
	}
	
	public static String sign(String str,String testsecret) throws Exception {
	
		String percentStr = "";
		String[] strs = str.split("&");
		for (int i = 0; i < strs.length;i++) {
			String[] str1 =strs[i].split("=");
			if(str1.length == 1){
			     percentStr = percentStr + getUtf8Encoder(str1[0])+ "=" + getUtf8Encoder("")+ "&";
			}else{
			     percentStr = percentStr + getUtf8Encoder(str1[0])+ "=" + getUtf8Encoder(str1[1]) + "&";
			}
		}
		percentStr =percentStr.substring(0,percentStr.lastIndexOf("&"));
		String percent = URLEncoder.encode("/","UTF-8");
		percentStr = getUtf8Encoder(percentStr);
		String toSign = HttpMethod.POST + "&"+ percent +"&" + percentStr;
		System.out.println("--------------"+ toSign);
		/*POST&%2F&AccessKeyId%3Dtestid%26AccountName%3D%253Ca%2525b%2527%253E%26Action%3DSingleSendMail%26AddressType%3D1%26Format%3DXML%26HtmlBody%3D4%26RegionId%3Dcn-hangzhou%26ReplyToAddress%3Dtrue%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3Dc1b2c332-4cfb-4a0f-b8cc-ebe622aa0a5c%26SignatureVersion%3D1.0%26Subject%3D3%26TagName%3D2%26Timestamp%3D2016-10-20T06%253A27%253A56Z%26ToAddress%3D1%2540test.com%26Version%3D2015-11-23*/
		byte[] bytes = HmacSHA1Encrypt(toSign,testsecret+"&");
		String base64Str = Base64.encode(bytes);
		System.out.println(base64Str);//llJfXJjBW3OacrVgxxsITgYaYm0=
		return base64Str;
	}
	
	private static String getUtf8Encoder(String param) throws UnsupportedEncodingException {
		return URLEncoder.encode(param, "UTF-8")
	                .replaceAll("\\+","%20")
	                .replaceAll("\\*","%2A")
	                .replaceAll("%7E","~");
	 };
}
